package com.reserv.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.reserv.dao.CommentDAO;
import com.reserv.dao.FacilityDAO;
import com.reserv.dao.ServiceDAO;
import com.reserv.util.TimestampUtil;
import com.reserv.vo.CommentVO;
import com.reserv.vo.FacilityVO;
import com.reserv.vo.ServiceVO;

public class ReservViewAction implements CommandProcess {

	@SuppressWarnings("unchecked")
	public ForwardAction requestProcess(
			HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {		
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();

		int sno = Integer.parseInt(request.getParameter("sno"));

		ServiceDAO sDao = ServiceDAO.getInstance();
		FacilityDAO fDao = FacilityDAO.getInstance();
		CommentDAO cDao = CommentDAO.getInstance();

		ServiceVO service = sDao.getVO(sno);
		FacilityVO facility = fDao.getVO(service.getFno());

		request.setAttribute("service", service);
		request.setAttribute("facility", facility);

		TimestampUtil tsu = new TimestampUtil();
		request.setAttribute("tsu", tsu);

		ArrayList<CommentVO> comments = 
				(ArrayList<CommentVO>) cDao.getListVOs(service.getFno());

		int total = 0;
		int avgGrade = 1;
		if(comments != null) {
			for(CommentVO comment : comments) {
				total += comment.getGrade();
			}
			avgGrade = total / comments.size();

			request.setAttribute("comments", comments);
			request.setAttribute("commentLen", comments.size());
			request.setAttribute("avgGrade", avgGrade);
		} else {
			request.setAttribute("commentLen", 0);
			request.setAttribute("avgGrade", avgGrade);
		}

		if(session.getAttribute("isLogin") != null) {
			ArrayList<ServiceVO> list = null;
			Object obj = session.getAttribute("sList");
			if(obj == null) {
				list = new ArrayList<>();
				list.add(service);
			} else {
				if(obj instanceof ArrayList<?>) {
					list = (ArrayList<ServiceVO>) obj;
					
					for(int i = 0; i < list.size(); i++) {
						ServiceVO s = list.get(i);
						if(service.getSno() == s.getSno()) {
							list.remove(i);
						}
					}
					list.add(0, service);
				}
			}
			session.setAttribute("sList", list);
		}

		ForwardAction forward = new ForwardAction();
		forward.setRedirect(false);
		if(service.getType().equals("gym"))
			forward.setPath("/main/index.jsp?body=/reserv/view.jsp&type=gym");
		else if(service.getType().equals("pub"))
			forward.setPath("/main/index.jsp?body=/reserv/view.jsp&type=pub");
		return forward;
	}
}